package com.campus.handler;

import com.campus.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 * @author TaiZai
 * @data 2024/10/21 18:07
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(Exception ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public Result<String> handleSQLException(SQLException ex) {
        log.error("SQL异常：{}", ex.getMessage());
        return Result.error("数据库操作失败，请稍后再试");
    }

    /**
     * 捕获数据库访问异常
     * @param ex
     * @return
     */
    @ExceptionHandler(DataAccessException.class)
    public Result<String> handleDataAccessException(DataAccessException ex) {
        log.info("数据库访问异常：", ex);
        return Result.error("数据库访问错误，请稍后再试");
    }
}
